<script setup lang="ts">
// 引入必要的模块和组件
import { ExamService } from "@/service/ExamService";
import { onMounted, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { CommonService } from "../common";
import ConfirmDialog from "../ConfirmDialog.vue";

// 定义引用变量
const confirmDialog = ref<InstanceType<typeof ConfirmDialog>>();
const dialogMessage = ref("正在保存试卷");

const route = useRoute();
const router = useRouter();

// 定义用户信息
const currentUser = ref({
    name: "",
    sn: "",
    r: 0,
});

// 考试管理相关
const exams = ref<any[]>([]);
const examDialog = ref(false);
const isEditingExam = ref(false);
const examForm = ref({
    Id: 0,
    Title: "",
    Desc: "",
    Enable: 1,
    Questions: "",
    StartAt: "", // 添加开始时间字段
    EndAt: ""    // 添加结束时间字段
});

// 定义题目列表（用于可视化编辑）
const questionList = ref<string[]>([]);

// 加载状态
const isLoading = ref(false);

// 挂载时执行的逻辑
onMounted(async () => {
    try {
        isLoading.value = true;
        // 获取授权信息
        const authorizationStr = localStorage.getItem("Authorization");
        const payload = CommonService.parseJwtPayload(authorizationStr);
        if (!payload) {
            router.push({ name: "login" });
            return;
        }
        currentUser.value = payload;

        // 只有教师角色才能访问此页面
        if (currentUser.value.r !== 1) {
            router.push({ name: "access" });
            return;
        }

        // 获取所有试卷
        await loadExams();
    } catch (error) {
        alert("加载出错: " + error);
    } finally {
        isLoading.value = false;
    }
});

// 打开确认对话框
const openDialog = () => {
    confirmDialog.value?.open();
};
const closeDialog = () => {
    confirmDialog.value?.cancelFun();
};

// 考试管理功能
const loadExams = async () => {
    try {
        const result = await ExamService.getAllExams();
        if (result.Code === 1000) {
            exams.value = result.Data;
        }
    } catch (error) {
        console.error("加载考试列表失败:", error);
    }
};

const openNewExam = () => {
    examForm.value = {
        Id: 0,
        Title: "",
        Desc: "",
        Enable: 1,
        Questions: "",
        StartAt: "",
        EndAt: ""
    };
    questionList.value = [];
    isEditingExam.value = false;
    examDialog.value = true;
};

const editExam = (exam: any) => {
    examForm.value = { ...exam };

    // 解析题目列表用于可视化编辑
    try {
        const questions = exam.Questions ? JSON.parse(exam.Questions) : [];
        questionList.value = Array.isArray(questions) ? questions : [];
    } catch (e) {
        console.warn("Failed to parse questions for exam:", exam.Id, e);
        questionList.value = [];
    }

    isEditingExam.value = true;
    examDialog.value = true;
};

const deleteExam = async (exam: any) => {
    if (confirm(`确定要删除考试 "${exam.Title}" 吗？`)) {
        try {
            const result = await ExamService.deleteExam(exam.Id);
            if (result.Code === 1000) {
                await loadExams();
                alert("删除成功");
            } else {
                alert("删除失败: " + result.Title);
            }
        } catch (error) {
            alert("删除失败: " + error);
        }
    }
};

const saveExam = async () => {
    try {
        // 将题目列表转换为JSON格式
        examForm.value.Questions = JSON.stringify(questionList.value);

        let result;
        if (isEditingExam.value) {
            // 更新考试
            result = await ExamService.updateExam(examForm.value.Id, examForm.value);
        } else {
            // 创建考试
            result = await ExamService.createExam(examForm.value);
        }

        if (result.Code === 1000) {
            examDialog.value = false;
            await loadExams();
            alert(isEditingExam.value ? "更新成功" : "创建成功");
        } else {
            alert((isEditingExam.value ? "更新" : "创建") + "失败: " + result.Title);
        }
    } catch (error) {
        alert((isEditingExam.value ? "更新" : "创建") + "失败: " + error);
    }
};

// 添加新题目
const addQuestion = () => {
    questionList.value.push("");
};

// 删除题目
const removeQuestion = (index: number) => {
    questionList.value.splice(index, 1);
};

// 更新题目内容
const updateQuestion = (index: number, value: string) => {
    questionList.value[index] = value;
};

const hideDialog = () => {
    examDialog.value = false;
};
</script>

<style scoped>
textarea:focus {
    background-color: #e8f5e9;
}

.loading {
    text-align: center;
    margin-top: 20px;
    font-size: 18px;
    color: #fff;
}

.student-info {
    text-align: center;
    font-size: 18px;
    color: #036d31;
}

.exam-management {
    margin: 20px;
    padding: 20px;
    background-color: #f8f9fa;
    border-radius: 8px;
}

.question-item {
    transition: box-shadow 0.2s;
    background-color: #fff;
}

.question-item:hover {
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.15) !important;
}

.question-textarea {
    border: 1px solid #ced4da;
    border-radius: 3px;
    padding: 6px;
    font-family: inherit;
    font-size: 14px;
}

.question-textarea:focus {
    outline: 0 none;
    outline-offset: 0;
    box-shadow: 0 0 0 0.1rem #c8e6c9;
    border-color: #4caf50;
}

:deep(.p-dialog .p-dialog-content) {
    background-color: #fafafa;
}

:deep(.p-dialog .p-dialog-header) {
    background-color: #4caf50;
    color: #fff;
}

:deep(.p-dialog .p-dialog-footer) {
    background-color: #fafafa;
    border-top: 1px solid #eee;
}

:deep(.p-button-success) {
    background-color: #4caf50;
    border-color: #4caf50;
}

:deep(.p-button-success:hover) {
    background-color: #43a047;
    border-color: #43a047;
}
</style>

<template>
    <div class="bg-surface-0 dark:bg-surface-900" style="padding-top: 0.1rem;">
        <!-- 显示教师信息 -->


        <div class="exam-management">

            <Button label="添加试卷" icon="pi pi-plus" @click="openNewExam" />

            <!-- 试卷列表 -->
            <div class="card">
                <DataTable :value="exams" responsiveLayout="scroll">
                    <Column field="Id" header="ID"></Column>
                    <Column field="Title" header="试卷标题"></Column>
                    <Column field="Desc" header="描述"></Column>
                    <Column field="StartAt" header="开始时间"></Column>
                    <Column field="EndAt" header="结束时间"></Column>
                    <Column header="状态">
                        <template #body="slotProps">
                            <span :class="slotProps.data.Enable ? 'text-green-500' : 'text-red-500'">
                                {{ slotProps.data.Enable ? '启用' : '禁用' }}
                            </span>
                        </template>
                    </Column>
                    <Column header="操作">
                        <template #body="slotProps">
                            <Button icon="pi pi-pencil" class="p-button-rounded p-button-success mr-2"
                                @click="editExam(slotProps.data)" />
                            <Button icon="pi pi-trash" class="p-button-rounded p-button-warning"
                                @click="deleteExam(slotProps.data)" />
                        </template>
                    </Column>
                </DataTable>
            </div>
        </div>

        <!-- 考试管理对话框 -->
        <Dialog v-model:visible="examDialog" header="试卷详情" :modal="true" class="p-fluid" :style="{ width: '65vw' }"
            :maximizable="true" appendTo="body">
            <div class="flex flex-column gap-2 p-2">
                <div class="flex gap-3" style="width: 50%;">
                    <div class="flex-grow">
                        <label for="title" class="font-bold block mb-1 text-sm">试卷标题</label>
                        <InputText id="title" v-model="examForm.Title" required autofocus class="w-full p-2" />
                    </div>
                    <div class="flex-none flex align-items-middle" style="width: 30%;">
                        <div class="flex align-items-center">
                            <Checkbox id="enable" v-model="examForm.Enable" :binary="true" :true-value="1"
                                :false-value="0" />
                            <label for="enable" class="ml-2 font-bold text-sm">启用</label>
                        </div>
                    </div>
                </div>


                <!-- 调整开始时间和结束时间在同一行 -->
                <div class="field ">
                    <label for="startAt" class="font-bold block mb-1 text-sm">开始时间</label>
                    <InputText id="startAt" type="datetime-local" v-model="examForm.StartAt" />

                </div>
                <div class="field ">
                    <label for="endAt" class="font-bold block mb-1 text-sm">结束时间</label>
                    <InputText id="endAt" type="datetime-local" v-model="examForm.EndAt" />

                </div>
                <div class="field mt-3" style="width: 250px;">
                    <Button icon="pi pi-plus" label="添加题目" @click="addQuestion" size="small" />
                </div>
            </div>
            <div class="field  col-12">
                <label for="desc" class="font-bold   mb-1 text-sm ">描述:</label>
                <InputText id="desc" v-model="examForm.Desc" required class="w-full p-2 text-sm" />
            </div>
            <div class="field col-12">


                <!-- 题目列表可视化编辑 -->
                <div class="question-list">
                    <div v-for="(question, index) in questionList" :key="index"
                        class="question-item p-3 mb-3 border-round shadow-1 w-full">
                        <div class="flex flex-column w-full">
                            <div class="flex align-items-center mb-2">
                                <span class="font-bold text-sm mr-2">Q{{ index + 1 }}:</span>
                            </div>
                            <div class="w-full mb-3">
                                <Textarea :autoResize="true" rows="2" class="w-full question-textarea p-2 text-sm"
                                    :value="question"
                                    @input="updateQuestion(index, ($event.target as HTMLTextAreaElement).value)"
                                    placeholder="请输入题目内容..." />
                            </div>
                            <div class="  flex justify-content-end">
                                <Button icon="pi pi-trash" rounded text severity="danger" @click="removeQuestion(index)"
                                    v-tooltip="'删除题目'" size="small" />
                            </div>
                        </div>
                    </div>

                    <div v-if="questionList.length === 0" class="text-center p-4 border-round">
                        <p class="m-0 text-sm">暂无题目，请点击"添加题目"按钮添加题目</p>
                    </div>
                </div>
            </div>
            <template #footer>
                <Button label="取消" icon="pi pi-times" class="p-button-text" @click="hideDialog" size="small" />
                <Button label="保存" icon="pi pi-check" @click="saveExam" class="p-button-success" size="small" />
            </template>
        </Dialog>

        <!-- 确认对话框 -->
        <ConfirmDialog :message="dialogMessage" ref="confirmDialog" />

        <!-- 页脚 -->
        <AppFooter />
    </div>
</template>
